package org.gitos.cloud.domain.device;

import java.util.List;

import org.gitos.cloud.domain.redis.DeviceRedisTemplate;
import org.gitos.cloud.domain.tcp.DeviceId;
import org.gitos.cloud.util.HexUtil;
import org.springframework.data.redis.core.BoundHashOperations;

/**
 * Created by shizhengchu on 16/3/14.
 */
public class Router {
    private DeviceRedisTemplate redisTemplate;
    private static final String DEVICE_KEY = "devicesKey";

    public Router(DeviceRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void registerDevice(Device device) {
        String key = HexUtil.encodeHexStr(device.getDeviceId().getValue());
        BoundHashOperations<String, String, Device> ops = redisTemplate
                .boundHashOps(DEVICE_KEY);
        ops.put(key, device);
    }

    public Device fetchDevice(DeviceId deviceId) {
        String key = HexUtil.encodeHexStr(deviceId.getValue());
        return fetchDevice(key);
    }

    public Device fetchDevice(String key) {
        BoundHashOperations<String, String, Device> ops = redisTemplate
                .boundHashOps(DEVICE_KEY);
        return ops.get(key);
    }

    public void deleteDevice(DeviceId deviceId) {
        String key = HexUtil.encodeHexStr(deviceId.getValue());
        deleteDevice(key);
    }

    public void deleteDevice(String key) {
        BoundHashOperations<String, String, Device> ops = redisTemplate
                .boundHashOps(DEVICE_KEY);
        ops.delete(key);
    }

    public List<Device> allDevice() {
        BoundHashOperations<String, String, Device> ops = redisTemplate
                .boundHashOps(DEVICE_KEY);
        return ops.values();

    }

}
